home *** CD-ROM | disk | FTP | other *** search
/ Total Network Tools 2002 / NextStepPublishing-TotalNetworkTools2002-Win95.iso / Archive / Misc Servers / Zope.exe / PCGISERVER.PY < prev    next >
Encoding:
Python Source  |  1999-11-23  |  16.4 KB  |  459 lines

  1. ##############################################################################
  2. # Zope Public License (ZPL) Version 1.0
  3. # -------------------------------------
  4. # Copyright (c) Digital Creations.  All rights reserved.
  5. # This license has been certified as Open Source(tm).
  6. # Redistribution and use in source and binary forms, with or without
  7. # modification, are permitted provided that the following conditions are
  8. # met:
  9. # 1. Redistributions in source code must retain the above copyright
  10. #    notice, this list of conditions, and the following disclaimer.
  11. # 2. Redistributions in binary form must reproduce the above copyright
  12. #    notice, this list of conditions, and the following disclaimer in
  13. #    the documentation and/or other materials provided with the
  14. #    distribution.
  15. # 3. Digital Creations requests that attribution be given to Zope
  16. #    in any manner possible. Zope includes a "Powered by Zope"
  17. #    button that is installed by default. While it is not a license
  18. #    violation to remove this button, it is requested that the
  19. #    attribution remain. A significant investment has been put
  20. #    into Zope, and this effort will continue if the Zope community
  21. #    continues to grow. This is one way to assure that growth.
  22. # 4. All advertising materials and documentation mentioning
  23. #    features derived from or use of this software must display
  24. #    the following acknowledgement:
  25. #      "This product includes software developed by Digital Creations
  26. #      for use in the Z Object Publishing Environment
  27. #      (http://www.zope.org/)."
  28. #    In the event that the product being advertised includes an
  29. #    intact Zope distribution (with copyright and license included)
  30. #    then this clause is waived.
  31. # 5. Names associated with Zope or Digital Creations must not be used to
  32. #    endorse or promote products derived from this software without
  33. #    prior written permission from Digital Creations.
  34. # 6. Modified redistributions of any form whatsoever must retain
  35. #    the following acknowledgment:
  36. #      "This product includes software developed by Digital Creations
  37. #      for use in the Z Object Publishing Environment
  38. #      (http://www.zope.org/)."
  39. #    Intact (re-)distributions of any official Zope release do not
  40. #    require an external acknowledgement.
  41. # 7. Modifications are encouraged but must be packaged separately as
  42. #    patches to official Zope releases.  Distributions that do not
  43. #    clearly separate the patches from the original work must be clearly
  44. #    labeled as unofficial distributions.  Modifications which do not
  45. #    carry the name Zope may be packaged in any form, as long as they
  46. #    conform to all of the clauses above.
  47. # Disclaimer
  48. #   THIS SOFTWARE IS PROVIDED BY DIGITAL CREATIONS ``AS IS'' AND ANY
  49. #   EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  50. #   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  51. #   PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL DIGITAL CREATIONS OR ITS
  52. #   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  53. #   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  54. #   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
  55. #   USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  56. #   ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  57. #   OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  58. #   OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  59. #   SUCH DAMAGE.
  60. # This software consists of contributions made by Digital Creations and
  61. # many individuals on behalf of Digital Creations.  Specific
  62. # attributions are listed in the accompanying credits file.
  63. ##############################################################################
  64.  
  65. """
  66. Medusa PCGI server.
  67.  
  68. This server functions as the PCGI publisher--it accepts the request
  69. from the PCGI wrapper CGI program, services the request, and sends
  70. back the response.
  71.  
  72. It should work with both inet and unix domain sockets.
  73.  
  74. Why would you want to use it? Using PCGI to connect to ZServer from
  75. another webserver is similar to using the web server as a proxy,
  76. with the difference, that the web server gets to control the 
  77. environment and headers completely.
  78.  
  79. Note that ZServer can operate multiple PCGI servers.
  80. """
  81.  
  82. from medusa import asynchat, asyncore, logger
  83. from medusa.counter import counter
  84. from medusa.http_server import compute_timezone_for_log
  85. from medusa.asyncore import compact_traceback
  86.  
  87. from ZServer import CONNECTION_LIMIT
  88.  
  89. from PubCore import handle
  90. from PubCore.ZEvent import Wakeup
  91. from ZPublisher.HTTPResponse import HTTPResponse
  92. from ZPublisher.HTTPRequest import HTTPRequest
  93. from Producers import ShutdownProducer, LoggingProducer, CallbackProducer
  94. import DebugLogger
  95.  
  96. from cStringIO import StringIO
  97. from tempfile import TemporaryFile
  98. import socket, string, os, sys, time
  99. from types import StringType, TupleType
  100.  
  101. tz_for_log=compute_timezone_for_log()
  102.  
  103. class PCGIChannel(asynchat.async_chat):    
  104.     """Processes a PCGI request by collecting the env and stdin and
  105.     then passing them to ZPublisher. The result is wrapped in a
  106.     producer and sent back."""
  107.  
  108.     closed=0
  109.     
  110.     def __init__(self,server,sock,addr):
  111.         self.server = server
  112.         self.addr = addr
  113.         asynchat.async_chat.__init__ (self, sock)
  114.         self.env={}
  115.         self.data=StringIO()
  116.         self.set_terminator(10)
  117.         self.size=None
  118.         self.done=None
  119.         
  120.     def found_terminator(self):
  121.         if self.size is None:
  122.             # read the next size header
  123.             # and prepare to read env or stdin
  124.             self.data.seek(0)
  125.             self.size=string.atoi(self.data.read())
  126.             self.set_terminator(self.size)
  127.             if self.size==0:
  128.             
  129.                 DebugLogger.log('I', id(self), 0)
  130.             
  131.                 self.set_terminator('\r\n') 
  132.                 self.data=StringIO()
  133.                 self.send_response()
  134.             elif self.size > 1048576:
  135.                 self.data=TemporaryFile('w+b')
  136.             else:
  137.                 self.data=StringIO()
  138.         elif not self.env:
  139.             # read env
  140.             self.size=None
  141.             self.data.seek(0)
  142.             buff=self.data.read()
  143.             for line in string.split(buff,'\000'):
  144.                 try:
  145.                     k,v = string.split(line,'=',1)
  146.                     self.env[k] = v
  147.                 except:
  148.                     pass
  149.             # Hack around broken IIS PATH_INFO
  150.             # maybe, this should go in ZPublisher...      
  151.             if self.env.has_key('SERVER_SOFTWARE') and \
  152.                     string.find(self.env['SERVER_SOFTWARE'],
  153.                     'Microsoft-IIS') != -1:
  154.                 script = filter(None,string.split(
  155.                         string.strip(self.env['SCRIPT_NAME']),'/'))
  156.                 path = filter(None,string.split(
  157.                         string.strip(self.env['PATH_INFO']),'/'))
  158.                 self.env['PATH_INFO'] = '/' + string.join(path[len(script):],'/')
  159.             self.data=StringIO()
  160.  
  161.             DebugLogger.log('B', id(self), 
  162.                 '%s %s' % (self.env['REQUEST_METHOD'],
  163.                            self.env.get('PATH_INFO' ,'/')))
  164.                 
  165.             # now read the next size header
  166.             self.set_terminator(10)
  167.         else:
  168.  
  169.             DebugLogger.log('I', id(self), self.terminator)     
  170.         
  171.             # we're done, we've got both env and stdin
  172.             self.set_terminator('\r\n')
  173.             self.data.seek(0)
  174.             self.send_response()
  175.         
  176.     def send_response(self):
  177.         # create an output pipe by passing request to ZPublisher,
  178.         # and requesting a callback of self.log with the module
  179.         # name and PATH_INFO as an argument.
  180.         self.done=1        
  181.         response=PCGIResponse(stdout=PCGIPipe(self), stderr=StringIO())
  182.         request=HTTPRequest(self.data, self.env, response)
  183.         handle(self.server.module, request, response)
  184.         
  185.     def collect_incoming_data(self, data):
  186.         self.data.write(data)
  187.  
  188.     def readable(self):
  189.         if not self.done:
  190.             return 1
  191.      
  192.     def log_request(self, bytes):
  193.         if self.env.has_key('PATH_INFO'):
  194.             path=self.env['PATH_INFO']
  195.         else:
  196.             path='%s/' % self.server.module
  197.         if self.env.has_key('REQUEST_METHOD'):
  198.             method=self.env['REQUEST_METHOD']
  199.         else:
  200.             method="GET"
  201.         addr=self.addr
  202.         if addr and type(addr) is TupleType:
  203.             self.server.logger.log (
  204.                 addr[0],
  205.                 '%d - - [%s] "%s %s" %d %d' % (
  206.                     addr[1],
  207.                     time.strftime (
  208.                     '%d/%b/%Y:%H:%M:%S ',
  209.                     time.gmtime(time.time())
  210.                     ) + tz_for_log,
  211.                     method, path, self.reply_code, bytes
  212.                     )
  213.                 )
  214.         else:
  215.             self.server.logger.log (
  216.                 '127.0.0.1',
  217.                 '- - [%s] "%s %s" %d %d' % (
  218.                     time.strftime (
  219.                     '%d/%b/%Y:%H:%M:%S ',
  220.                     time.gmtime(time.time())
  221.                     ) + tz_for_log,
  222.                     method, path, self.reply_code, bytes
  223.                     )
  224.                 )       
  225.  
  226.     def push(self, producer, send=1):
  227.         # this is thread-safe when send is false
  228.         # note, that strings are not wrapped in 
  229.         # producers by default
  230.         self.producer_fifo.push(producer)
  231.         if send: self.initiate_send()
  232.         
  233.     def __repr__(self):
  234.         return "<PCGIChannel at %x>" % id(self)
  235.  
  236.     def close(self):
  237.         self.closed=1
  238.         while self.producer_fifo:
  239.             p=self.producer_fifo.first()
  240.             if p is not None and type(p) != StringType:
  241.                 p.more() # free up resources held by producer
  242.             self.producer_fifo.pop()
  243.         asyncore.dispatcher.close(self)          
  244.  
  245.  
  246. class PCGIServer(asyncore.dispatcher):
  247.     """Accepts PCGI requests and hands them off to the PCGIChannel for
  248.     handling.
  249.         
  250.     PCGIServer can be configured with either a PCGI info file or by
  251.     directly specifying the module, pid_file, and either port (for
  252.     inet sockets) or socket_file (for unix domain sockets.)
  253.  
  254.     For inet sockets, the ip argument specifies the address from which
  255.     the server will accept connections, '' indicates all addresses. If
  256.     you only want to accept connections from the localhost, set ip to
  257.     '127.0.0.1'."""
  258.         
  259.     channel_class=PCGIChannel
  260.  
  261.     def __init__ (self,
  262.             module='Main',
  263.             ip='127.0.0.1',
  264.             port=None,
  265.             socket_file=None,
  266.             pid_file=None,
  267.             pcgi_file=None,
  268.             resolver=None,
  269.             logger_object=None):
  270.  
  271.         self.ip = ip
  272.         asyncore.dispatcher.__init__(self)
  273.         self.count=counter()
  274.         if not logger_object:
  275.             logger_object = logger.file_logger (sys.stdout)
  276.         if resolver:
  277.             self.logger = logger.resolving_logger (resolver, logger_object)
  278.         else:
  279.             self.logger = logger.unresolving_logger (logger_object)
  280.         
  281.         # get configuration
  282.         self.module=module    
  283.         self.port=port
  284.         self.pid_file=pid_file
  285.         self.socket_file=socket_file
  286.         if pcgi_file is not None:
  287.             self.read_info(pcgi_file)
  288.         
  289.         # write pid file
  290.         try:
  291.            f = open(self.pid_file, 'w')
  292.            f.write(str(os.getpid()))
  293.            f.close()
  294.         except IOError:
  295.             self.log_info("Cannot write PID file.", 'error')
  296.         
  297.         # setup sockets
  298.         if self.port:
  299.             self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
  300.             self.set_reuse_addr()
  301.             self.bind((self.ip, self.port))
  302.             self.log_info(
  303.                 'PCGI Server started at %s\n'
  304.                 '\tInet socket port: %s' % (time.ctime(time.time()), self.port)
  305.                 )
  306.         else:
  307.             try:
  308.                 os.unlink(self.socket_file)
  309.             except os.error:
  310.                 pass
  311.             self.create_socket(socket.AF_UNIX, socket.SOCK_STREAM)
  312.             self.set_reuse_addr()
  313.             self.bind(self.socket_file)
  314.             try:
  315.                 os.chmod(self.socket_file,0777)
  316.             except os.error:
  317.                 pass
  318.             self.log_info(
  319.                 'PCGI Server started at %s\n' 
  320.                 '\tUnix socket: %s' % (time.ctime(time.time()), self.socket_file)
  321.                 )
  322.         self.listen(256)
  323.  
  324.  
  325.     def read_info(self,info_file):
  326.         "read configuration information from a PCGI info file"
  327.         lines=open(info_file).readlines()
  328.         directives={}
  329.         try:
  330.             for line in lines:
  331.                 line=string.strip(line)
  332.                 if not len(line) or line[0]=='#':
  333.                     continue
  334.                 k,v=string.split(line,'=',1)
  335.                 directives[string.strip(k)]=string.strip(v)
  336.         except:
  337.             raise 'ParseError', 'Error parsing PCGI info file'
  338.         
  339.         self.pid_file=directives.get('PCGI_PID_FILE',None)
  340.         self.socket_file=directives.get('PCGI_SOCKET_FILE',None)
  341.         if directives.has_key('PCGI_PORT'):
  342.             self.port=string.atoi(directives['PCGI_PORT'])
  343.         if directives.has_key('PCGI_MODULE'):
  344.             self.module=directives['PCGI_MODULE']
  345.         elif directives.has_key('PCGI_MODULE_PATH'):
  346.             path=directives['PCGI_MODULE_PATH']
  347.             path,module=os.path.split(path)
  348.             module,ext=os.path.splitext(module)
  349.             self.module=module
  350.         
  351.     def handle_accept (self):
  352.         self.count.increment()
  353.         try:
  354.             conn, addr = self.accept()
  355.         except socket.error:
  356.             self.log_info('Server accept() threw an exception', 'warning')
  357.             return
  358.         self.channel_class(self, conn, addr)
  359.    
  360.     def readable(self):
  361.         return len(asyncore.socket_map) < CONNECTION_LIMIT
  362.  
  363.     def writable (self):
  364.         return 0
  365.     
  366.     def listen(self, num):
  367.         # override asyncore limits for nt's listen queue size
  368.         self.accepting = 1
  369.         return self.socket.listen (num)
  370.         
  371.         
  372. class PCGIResponse(HTTPResponse):
  373.  
  374.     def write(self, data):
  375.         if not self._wrote:
  376.             self.stdout.write(str(self))
  377.             self._wrote=1
  378.         self.stdout.write(data)
  379.                                             
  380.     def _finish(self):
  381.         self.stdout.finish(self)
  382.         self.stdout.close()
  383.  
  384.         self.stdout=None
  385.         self._request=None
  386.         
  387.         
  388. class PCGIPipe:
  389.     """
  390.     Formats a HTTP response in PCGI format
  391.     
  392.         10 digits indicating len of STDOUT
  393.         STDOUT
  394.         10 digits indicating len of STDERR
  395.         STDERR
  396.     
  397.     Note that this implementation never sends STDERR
  398.     """
  399.     def __init__(self, channel):
  400.         self._channel=channel
  401.         self._data=StringIO()
  402.         self._shutdown=0
  403.     
  404.     def write(self,text):
  405.         self._data.write(text)
  406.         
  407.     def close(self):
  408.         if not self._channel.closed:
  409.             data=self._data.getvalue()
  410.             l=len(data)
  411.             DebugLogger.log('A', id(self._channel), 
  412.                 '%s %s' % (self._channel.reply_code, l))
  413.             self._channel.push('%010d%s%010d' % (l, data, 0), 0)
  414.             self._channel.push(LoggingProducer(self._channel, l, 'log_request'), 0)        
  415.             self._channel.push(CallbackProducer(
  416.                 lambda t=('E', id(self._channel)): apply(DebugLogger.log,t)), 0)
  417.  
  418.             if self._shutdown:
  419.                 try: r=self._shutdown[0]
  420.                 except: r=0
  421.                 sys.ZServerExitCode=r
  422.                 self._channel.push(ShutdownProducer(), 0)
  423.                 Wakeup(lambda: asyncore.close_all())
  424.             else:
  425.                 self._channel.push(None, 0)
  426.                 Wakeup()
  427.         self._data=None
  428.         self._channel=None
  429.         
  430.     def finish(self, response):
  431.         if response.headers.get('bobo-exception-type','') == \
  432.                 'exceptions.SystemExit':
  433.             r=response.headers.get('bobo-exception-value','0')
  434.             try: r=string.atoi(r)
  435.             except: r = r and 1 or 0
  436.             self._shutdown=r,
  437.         self._channel.reply_code=response.status
  438.